/**
 * 
 */
package com.hs.core.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.hs.auth.AUTHConstant;
import com.hs.auth.model.HsAccount;
import com.hs.core.db.DBMgr;
import com.hs.core.model.BaseBean;

/**
 * @author shl
 *
 * Dec 9, 2010
 */
public abstract class BaseAction {
	/**
	 * 获取当前登录用户
	 * @param request
	 * @return
	 */
	protected HsAccount getCurrentuser(HttpServletRequest request){
		HsAccount accInfo = (HsAccount)this.getSession(request).getAttribute(AUTHConstant.USERINSESSION); 
	 	   return  accInfo; 
	}
	/**
	 * 获取当前session
	 * @param request
	 * @return
	 */
	protected HttpSession getSession(HttpServletRequest request){
		if(null == request)
			return null;
		return request.getSession();
	}
	/**
	 *初始化用户信息于session
	 * @param request
	 * @return
	 */
	protected void initSession(HttpServletRequest request,BaseBean obj){
		 HttpSession session = this.getSession(request);
		 if(null != session){
			 session.setAttribute(AUTHConstant.USERINSESSION, obj);
			 System.out.println("initSession:" + session.getAttribute(AUTHConstant.USERINSESSION));
		 }
			 
	}
	/**
	 * 加载用户权限
	 * @param request
	 * @param accid
	 */
	protected void loadAuth(HttpServletRequest request,String accid){
		 DBMgr dbo = this.getDbo(request);
		 List roleList = dbo.queryList("select ROLECODE from HS_ROLE WHERE ID IN (SELECT ROLEID FROM HS_ACCROLE where accid=?)", new Object[]{accid});
		 Map authmap = new HashMap();
		 for(int i =0;i<roleList.size();i++){
			 Map data = (Map)roleList.get(i);
			 String roleCode = (String)data.get("ROLECODE");  
			 authmap.put(roleCode, roleCode);
		 }
		 
		 HttpSession session = this.getSession(request);
		 if(null != session){
			  session.setAttribute("USERPOWER_"+accid, authmap);
		 }
			 
	}
	/**
	 * 获取当前登录用户的权限
	 * @param request
	 * @param roleCode
	 * @return
	 */
	protected String getAuthByRoleCode(HttpServletRequest request,String roleCode){
		 HttpSession session = this.getSession(request);
		 if(null != session){
			 HsAccount accObj = this.getCurrentuser(request);
			 Map authMap = (Map)session.getAttribute("USERPOWER_"+accObj.getId());
			 if(null != authMap){
				 return (String)authMap.get(roleCode);
			 }
		 }
		 return null;
	}
	protected DBMgr getDbo(HttpServletRequest request){
		   return  DBMgr.getDbUtilInst(request.getSession().getServletContext());
	   }
	
	
}
